package com.tarena.lbs.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.basic.dao.repository.AreaRepository;
import com.tarena.lbs.basic.pojo.po.AreaPO;
import com.tarena.lbs.basic.pojo.vo.AreaVO;
import com.tarena.lbs.basic.service.AreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AreaServiceImpl implements AreaService {
    @Autowired
    private AreaRepository areaRepository;
    @Override
    public List<AreaVO> getAreaList(Integer parentId) {
        List<AreaPO> pos = getChildren(parentId);
        List<AreaVO> vos = null;
        if(pos != null && pos.size()>0){
            vos = pos.stream().map(po->{
                AreaVO vo = new AreaVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        return vos;
    }

    private List<AreaPO> getChildren(Integer parentId) {
        QueryWrapper<AreaPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",parentId);
        return areaRepository.list(queryWrapper);
    }

    @Override
    public List<AreaVO> tree() {
        List<AreaPO> pos = areaRepository.list();
        log.info("获取行政区域数据总量:{}",pos.size());
        return assembleAreaTree(pos);
    }

    private List<AreaVO> assembleAreaTree(List<AreaPO> pos) {
        List<AreaPO> provincePos =
                pos.stream().filter(po -> po.getParentId()!=null
                        &&po.getParentId()==0l).collect(Collectors.toList());
        log.info("获取省份数据总量:{}",provincePos);
        List<AreaVO> provinceVos = pos2vos(provincePos);
        for (AreaVO provinceVo : provinceVos){
            long provinceId = provinceVo.getId();
            List<AreaPO> cityPos = pos.stream().filter(po -> po.getParentId()!=null
                    &&po.getParentId()==provinceId).collect(Collectors.toList());
            List<AreaVO> cityVos = pos2vos(cityPos);
            provinceVo.setChildren(cityVos);
            for(AreaVO cityVo : cityVos){
                long cityId = cityVo.getId();
                List<AreaPO> areaPOs = pos.stream().filter(po -> po.getParentId()!=null
                        &&po.getParentId()==cityId).collect(Collectors.toList());
                List<AreaVO> areaVOS = pos2vos(areaPOs);
                cityVo.setChildren(areaVOS);
            }
        }
        return provinceVos;
    }

    private List<AreaVO> pos2vos(List<AreaPO> pos) {
        return pos.stream().map(po->{
            AreaVO vo = new AreaVO();
            BeanUtils.copyProperties(po,vo);
            return vo;
        }).collect(Collectors.toList());
    }
}
